import os
import time
import datetime


def format_number(num, bit_num=2):
    s = str(num)
    if len(s) > bit_num:
        raise "number's bit longer than max bit"

    s = s if len(s) == bit_num else "0" * (bit_num - len(s)) + s
    return s


def format_date(sep=None, hours=None):
    # if sep is None
    default = ["年", "月", "日"]
    hours_default = ["时", "分"]
    dates = time.localtime()
    year = str(dates.tm_year)
    month = dates.tm_mon
    day = dates.tm_mday

    month = str(month) if month > 9 else "0" + str(month)
    day = str(day) if day > 9 else "0" + str(day)
    s = year + "{}" + month + "{}" + day + "{}"
    if sep is None:
        s = s.format(*default)
    else:
        s = s.format(sep, sep, sep)

    if hours is not None:
        hours_str = format_number(dates.tm_hour) + "{}" + format_number(dates.tm_min) + "{}"
        if hours == 'default':
            hours_str = hours_str.format(*hours_default)
        else:
            hours_str = hours_str.format(hours, hours)

        s += "_" + hours_str

    return s


def create_folder(path, date):
    dir_path = os.path.join(path, date)
    if not os.path.exists(dir_path):
        os.mkdir(dir_path)


def get_sec(hour, tm_min, sec):
    return hour * 3600 + tm_min * 60 + sec


def get_file_idx(timestamp):
    dates = datetime.datetime.now()
    idx = -1
    for i, it in enumerate(timestamp[::-1]):
        if get_sec(*it) < get_sec(dates.hour, dates.minute, dates.second) - 60.0:
            idx = len(timestamp) - i - 1
            break
    return idx, dates


def get_file_path(timestamp):
    idx, dates = get_file_idx(timestamp)

    if idx == -1:
        last = dates - datetime.timedelta(days=1)
        s = str(last.year) + format_number(last.month) + format_number(last.day) + "_"

    else:
        s = str(dates.year) + format_number(dates.month) + format_number(dates.day) + "_"

    s += format_number(timestamp[idx][0]) + format_number(timestamp[idx][1])
    return s


def get_nearest_file(path, today):
    folders = os.listdir(path)
    if today in folders:
        folders.remove(today)

    if len(folders) == 0:
        raise "no initial file"

    folders = sorted(folders)

    target_folder = folders[-1]

    files = sorted(os.listdir(os.path.join(path, target_folder)))
    return os.path.join(path, target_folder, files[-1])


def sort_timestamp(timestamp):
    res = sorted(timestamp, key=lambda x: x[0] * 3600 + x[1] * 60 + x[2])
    return res


if __name__ == "__main__":
    time_stamp = [[11, 39, 0], [11, 51, 0], [11, 52, 0], [11, 53, 0]]
    # print(sort_timestamp([[18, 0, 0], [12, 0, 0], [16, 0, 0]]))
    print(get_file_idx(time_stamp))
    print(get_file_path(time_stamp))
